<template>
	<view class="text-df page">
		<view class="banner">
			<swiper class="banner_swiper" indicator-dots indicator-active-color="#DE483D">
				<swiper-item class="banner_swiper_item" v-for="(item,index) in productDetail.bannerList" :key="index">
					<image @click="onPreviewImage(item,productDetail.bannerList)" class="banner_swiper_item_image" :src="item" mode="aspectFill"></image>
				</swiper-item>
			</swiper>
			<button open-type="share" class="banner_share l-f l-row-c">
				<uni-icons type="redo" size="50rpx" color="#ffffff"></uni-icons>
				<view class="banner_share_label">分享</view>
			</button>
		</view>

		<!-- 基本信息 -->
		<view class="bg-white padding-com ">
			<view class="text-low text-sm" style="text-align: right;">
				<text class="margin-right-xs">线上库存：{{productDetail.stock}}</text>
				<text>销量：{{productDetail.sales}}</text>
			</view>
			<view class="theme-color text-bold">
				<text>￥</text>
				<text class="text-xxl">{{productDetail.price}}</text>
			</view>
			<view class="text-bold text-lg margin-top-xs">{{productDetail.storeName}}</view>
			<!-- 规格选择 -->
			<view class="l-f select-info" @click="onSelect" hover-class="hover-class">
				<view class="select-info_label">已选</view>
				<view class="select-info_value l-f1">{{selectName ? selectName : '请选择规格'}}</view>
				<uni-icons type="right" size="30rpx" color="#5e6d82"></uni-icons>
			</view>
			<view class="flex-row-bt">
				<view class="theme-color flex-row padding-top-xs">
					<view class=" flex-row">
						<uni-icons type="checkbox" size="18" color="#EE3F4D"></uni-icons>
						<view class="text-sm" style="margin: 2rpx 0 0 0;">门店自提</view>
					</view>
					<view class=" flex-row margin-left-xs">
						<uni-icons type="checkbox" size="18" color="#EE3F4D"></uni-icons>
						<view class="text-sm" style="margin: 2rpx 0 0 0;">同城配送</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 商品详情 -->
		<view class="margin-top-sm bg-white padding-com">
			<view class="flex-row margin-bottom-sm">
				<view style="" class="vertical-line theme-bg-color"></view>
				<text class="text-lg margin-left-xs" style="">商品详情</text>
			</view>
			<divider v-if="productDetail.content==null || productDetail.content==''"></divider>
			<uv-parse v-else :content="productDetail.content"></uv-parse>
		</view>
		<!-- 底部按钮 -->
		<bottom-btn :cartNum="cartNum" @add="onAddCart" @buy="onBuy" />
		<!-- 规格弹窗 -->
		<uni-popup ref="popupRef" type="bottom" :is-mask-click="false">
			<view class="spec-popup">
				<view @click="onCloseSpec" class="spec-popup_close l-f l-row-c" hover-class="hover-class">
					<uni-icons type="closeempty" size="28" color="#5e6d82"></uni-icons>
				</view>
				<!-- 详情 -->
				<view class="spec-popup_info l-f l-col-end">
					<view class="spec-popup_info_left">
						<image 
						@click="onPreviewImage(currentImage,[currentImage])"
						class="spec-popup_info_left_cover" 
						:src="currentImage" 
						mode="aspectFill"></image>
					</view>
					<view class="spec-popup_info_right">
						<view>
							<text class="spec-popup_info_right_unit">￥</text>
							<text class="spec-popup_info_right_price">{{currentProductObj.price ? currentProductObj.price : productDetail.price}}</text>
						</view>
						<view class="spec-popup_info_right_number">库存{{totalStock}}件</view>
						<view class="spec-popup_info_right_select l-line1"
						:class="selectName ? '' : 'spec-popup_info_right_placeholder'">已选： {{selectName ? selectName : '请选择规格'}}</view>
					</view>
				</view>
				<!-- 选择 -->
				<scroll-view scroll-y="true" class="spec-popup_scroll l-mg-top20">
					<select-box
					v-for="(item,index) in productList" 
					:key="index"
					:title="item.name" 
					:list="item.list"
					:current="productColumns[index]"
					@change="selectChange(index,$event)"></select-box>
				</scroll-view>
				<!-- 数量 -->
				<view class="spec-popup_number l-f l-row-sb">
					<view class="spec-popup_number_label">数量</view>
					<number-input v-model="buyNum" @add="onAddNum" @sub="onSubNum" :max="totalStock" />
				</view>
				<!-- 确定 -->
				<view class="spec-popup_submit l-f l-row-c">
					<view v-if="popupType === 'join'" @click="onJoinCart" 
					class="spec-popup_submit_item spec-popup_submit_join" 
					:class="buyNum <= 0 ? 'spec-popup_submit_item-disabled' : ''"
					hover-class="hover-class" >加入购物车</view>
					<view @click="onOrderBuy" v-else-if="popupType === 'buy'" class="spec-popup_submit_item spec-popup_submit_buy" hover-class="hover-class">立即购买</view>
					<view v-else @click="onCloseSpec" class="spec-popup_submit_item spec-popup_submit_select" hover-class="hover-class">确 定</view>
				</view>
			</view>
		</uni-popup>
		<!-- 加入购物车动画 -->
		<join-cart-animate ref="joinCartAnimateRef" :image="productDetail.image" />
		<!-- 接口请求加载动画 -->
		<loading></loading>
	</view>
</template>

<script setup lang="ts">
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		ref,
		reactive,
		computed
	} from "vue";
	import { 
		getProductDetail,
		postJoinCart,
	} from "@/api/product/index.ts";
	import { useStore } from 'vuex'
	
	const store = useStore();
	// 购物车数量
	const cartNum = computed(() => store.state.cartCount);
	// 当前商品id
	let currentId = ref('')
	// 商品详情
	let productDetail = reactive({
		bannerList: [], // 轮播
		stock: 0, // 总库存
		sales: 0, // 总销量
		storeName: '', // 商品名称
		unitName: '', // 单位
		content: '', // 商品详情
		storeInfo: '', // 商品简介
		price: '', // 商品价格
		image: '' // 封面图
	})
	const productList = ref([]) // 规格列表
	const productColumns = ref([]) // 规格选择下标
	let productValueObj = reactive({}) // 所有规格属性对象
	// 当前选中产品
	let currentProductObj = reactive({
		id: null, // id
		image: '', // 主图
		price: '', // 售价
	})
	// 购买数量
	let buyNum = ref(1)
	let popupType = ref('select') // 弹窗类型 select:选择 join:加入购物车 buy:立即购买

	const popupRef = ref(null)
	const joinCartAnimateRef = ref(null)
	
	// 获取当前封面显示
	const currentImage = computed(() => {
		return currentProductObj.image ? currentProductObj.image : productDetail.image
	})
	
	// 计算库存
	const totalStock = computed(() => {
		let total = 0
		let filterProductValueObj = {...productValueObj}
		let isSelect = false // 判断是否存在选择
		// 过滤选择的规格
		for (let i = 0; i < productColumns.value.length; i++) {
			let currentColumn = productColumns.value[i]
			let currentProduct = productList.value[i]
			if(currentColumn > -1) {
				if(!isSelect) {
					isSelect = true
				}
				let filterObj = {}
				// 判断key是否相等
				for (let key in filterProductValueObj) {
					if(currentProduct.list[currentColumn].label === filterProductValueObj[key].attrValue[productList.value[i].name]) {
						filterObj[key] = filterProductValueObj[key]
					}
				}
				filterProductValueObj = {...filterObj}
			}
		}
		let productArr = []
		// 遍历符合条件商品
		for (let key in filterProductValueObj) {
			total += filterProductValueObj[key].stock
			productArr.push(filterProductValueObj[key])
		}
		// 当前选择商品-默认第一个
		if(productArr.length > 0 && isSelect) {
			currentProductObj.id = productArr[0].id
			currentProductObj.image = productArr[0].image
			currentProductObj.price = productArr[0].price
		}
		return total
	})
	// 计算选择显示
	const selectName = computed(() => {
		let nameArr = []
		for (let i = 0; i < productList.value.length; i++) {
			if(productColumns.value[i] > -1) {
				nameArr.push(productList.value[i].list[productColumns.value[i]].label)
			}
		}
		if(nameArr.length > 0) {
			return nameArr.join(' | ')
		}
		return ''
	})

	onLoad((option) => {
		currentId.value = option.id
		//请求商品详情
		getDetail()
	})
	// 加数量
	const onAddNum = () => {
		// 判断是否超出库存
		if(buyNum.value >= totalStock.value) return
		buyNum.value += 1
	}
	// 减数量
	const onSubNum = () => {
		// 判断是否低于库存
		if(buyNum.value <= 1) return
		buyNum.value -= 1
	}
	// 规格选择显示
	const onSelect = () => {
		popupType.value = 'select'
		onShowSpec()
	}
	// 加入购物车显示
	const onAddCart = () => {
		popupType.value = 'join'
		onShowSpec()
	}
	// 购买显示
	const onBuy = () => {
		popupType.value = 'buy'
		onShowSpec()
	}
	// 规格显示
	const onShowSpec = () => {
		popupRef.value.open()
	}
	// 规格隐藏
	const onCloseSpec = () => {
		popupRef.value.close()
	}
	// 规格选择
	const selectChange = (index,value) => {
		productColumns.value[index] = productColumns.value[index] === value ? -1 : value
		// 商品规格匹配
		for (let i = 0; i < productList.value.length; i++) {
			let keyName = productList.value[i].name
			let currentKeyName = productList.value[index].name
			// 判断除当前选择的以外规格
			if(index !== i) {
				// 获取属性相同的
				for (let key in productValueObj) {
					if(productList.value[index].list[value].label === productValueObj[key].attrValue[currentKeyName]) {
						// 判断库存
						for (let j = 0; j < productList.value[i].list.length; j++) {
							if(productList.value[i].list[j].label === productValueObj[key].attrValue[keyName]){
								productList.value[i].list[j].disabled = productValueObj[key].stock <= 0 ? true : false
							}
						}
					}
				}
			}
		}
	
	}
	// 小图预览
	const onPreviewImage = (url: string,list: Array<string>) => {
		uni.previewImage({
			urls: list,
			current: url
		})
	}
	// 加入购物车
	const onJoinCart = async () => {
		if(buyNum.value <= 0) return
		// 判断是否规格选项全部勾选
		let isSelectAll = true
		for (let i = 0; i < productColumns.value.length; i++) {
			if(productColumns.value[i] < 0) {
				isSelectAll = false
				uni.showToast({
					title: '请选择' + productList.value[i].name,
					icon: 'none'
				})
				break
			}
		}
		if(isSelectAll) {
			const res = await postJoinCart({
				cartNum: buyNum.value,
				productAttrUnique: currentProductObj.id,
				productId: currentId.value
			})
			if(res.code === 200) {
				joinCartAnimateRef.value.start()
				store.dispatch('getCartNumData')
				onCloseSpec()
			}
		}
	}
	// 直接购买
	const onOrderBuy = () => {
		uni.navigateTo({
			url: '/pages/supermarket/orders'
		})
	}
	// 商品详情
	const getDetail = async () => {
		const res = await getProductDetail({
			id: currentId.value,
		})
		const {code,data} = res
		if(code === 200) {
			const {productInfo,productAttr,productValue} = data
			// 轮播图处理
			let bannerArr = []
			try{
				bannerArr = JSON.parse(productInfo.sliderImage)
			}catch(e){
				//TODO handle the exception
			}
			productDetail.bannerList = bannerArr // 轮播
			productDetail.stock = productInfo.stock // 总库存
			productDetail.sales = productInfo.sales // 总销量
			productDetail.storeName = productInfo.storeName // 商品名称
			productDetail.unitName = productInfo.unitName // 单位
			productDetail.content = productInfo.content // 商品详情
			productDetail.storeInfo = productInfo.storeInfo // 商品简介
			productDetail.price = productInfo.price // 商品价格
			productDetail.image = productInfo.image // 商品封面图
			
			// 商品规格处理
			let productArr = []
			let productColumnsArr = []
			for (let i = 0; i < productAttr.length; i++) {
				let list = []
				try{
					let attrArr = productAttr[i].attrValues.split(',')
					// 追加属性上去
					for (let j = 0; j < attrArr.length; j++) {
						list.push({
							label: attrArr[j],
							disabled: false
						})
					}
				}catch(e){
					console.log('产品规格解析失败',productAttr[i].attrValues)
				}
				productArr.push({
					name: productAttr[i].attrName,
					list
				})
				productColumnsArr.push(-1)
			}
			productList.value = productArr
			productColumns.value = productColumnsArr
			// 商品规格详情处理
			for (let key in productValue ) {
				try{
					productValue[key].attrValue = JSON.parse(productValue[key].attrValue)
				}catch(e){
					productValue[key].attrValue = {}
				}
			}
			productValueObj = productValue
			// 判断是否只有一个规格
			if(productColumns.value.length === 1) {
				// 一个规格默认选中
				selectChange(0,0)
			}
		}
	}
</script>

<style lang="scss" scoped>
@import "./detail.scss";
</style>